<!--
 * @Author: 瞿旺兴 18774621495@163.com
 * @Date: 2022-05-19 14:22:36
 * @LastEditors: 瞿旺兴 18774621495@163.com
 * @LastEditTime: 2022-06-15 09:33:07
 * @FilePath: \nien-vue3-admin\src\views\finance\receiverManame\reconciliationManagement\Receivable\collectionManage\collectionManager\components\AddFinancial.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-dialog 
    v-model="visible"
    :title="`${title}财务`"
    :before-close="cancel"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
    >
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="客户名称" prop="customerCode">
            <dictSelect 
              v-model="formData.customerCode"
              :disabled="title !== '新增'"
              dicts-name="客户"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="账单编号" prop="receivingAccount">
            <el-input v-model="formData.receivingAccount"></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="收款账号" prop="receivingAccount">
            <collectionAccount v-model="formData.receivingAccount" />
          </el-form-item>
        </el-col>
        <el-col v-if="title === '新增'" :span="8">
          <el-form-item label="收款时间" prop="receivingDate">
            <el-date-picker
              v-model="formData.receivingDate"
              type="date"
              clearable
              placeholder="选择日期"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="转入方名称" prop="transfereeAccountName">
            <el-input
              v-model="formData.transfereeAccountName"
              autosize
              clearable
              placeholder=""
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收款总金额" prop="amount">
            <el-input-number
              v-model="formData.amount"
              style="width: 100%"
              :controls="false"
              clearable
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="账单总金额" prop="billTotalAmount">
            <el-input-number
              v-model="formData.billTotalAmount"
              style="width: 100%"
              :disabled="true"
              :controls="false"
              clearable
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="币种" prop="currency">
            <dictSelect 
              v-model="formData.currency"
              :disabled="title !== '新增'"
              dicts-name="币种"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="汇率" prop="exchangeRate">
            <el-select
              v-model="formData.exchangeRate"
              :disabled="formData.currency === '1' || title !== '新增'"
            >
              <el-option
                v-for="item in currencyList"
                :key="item.id"
                :label="item.exchangeRate"
                :value="item.exchangeRate"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="汇率金额" prop="exchangeRateAmount">
            <el-input v-model="formData.exchangeRateAmount"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收款备注" prop="receivingRemarks">
            <el-input v-model="formData.receivingRemarks"></el-input>
          </el-form-item>
        </el-col>
        <el-col v-if="title === '新增'" :span="8">
          <el-form-item label="是否开票" prop="isBilling">
            <el-radio-group v-model="formData.isBilling">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="图片" class="uploadBox">
            <el-upload
              ref="upload"
              class="upload-demo"
              multiple
              action="#"
              accept="image/png,image/jpg,image/jpeg"
              :http-request="uploadFile"
              :file-list="fileList"
              :before-upload="(file) => beforeAvatarUpload(file)"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div>
        <el-button type="info" @click="cancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="confirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, defineEmits, defineExpose, reactive, watch, nextTick } from 'vue'
import * as imageConversion from 'image-conversion'
import { DictDirection } from '@/store/modules/dicts'
import { exchangeList } from '@/api/finance/FinancialManagementTools'
import { collectionManagerAdd, collectionManagerEdit } from '@/api/finance/receiverManange'
import { validateForm } from '@/utils'

const emits = defineEmits(['success'])
const title = ref('')
const formRef = ref(null)
const visible = ref<boolean>(false)   
const loading = ref<boolean>(false)   
const currencyList = ref<any[]>([])
const formData = reactive({
  id: undefined,
  customerCode: undefined,
  receivingAccount: undefined,
  receivingDate: undefined,
  transfereeAccountName: undefined,
  billTotalAmount: undefined,
  currency: undefined,
  exchangeRate: undefined,
  exchangeRateAmount: undefined,
  isBilling: undefined,
  receivingRemarks: undefined,
  amount: undefined,
  serialNoAmountVos: [
    {
      amount: undefined,
      serialNo: '',
      accountDate: '',
    },
  ],
})
const fileList = ref([])
const rules = {
  currency: [{ required: true, message: '请输入汇率', trigger: 'blur' }],
  exchangeRate: [{ required: true, message: '请输入币种', trigger: 'blur' }],
  exchangeRateAmount: [{ required: true, message: '请输入汇率金额', trigger: 'blur' }],
  isBilling: [{ required: true, message: '请选择是否开票', trigger: 'change' }],
  transfereeAccountName: [{ required: true, message: '请输入转入方名称', trigger: 'change' }],
  customerCode: [
    {
      required: true,
      message: '客户名称不能为空',
      trigger: ['change', 'blur'],
    },
  ],
  receivingAccount: [
    {
      required: true,
      message: '收款账号不能为空',
      trigger: ['change', 'blur'],
    },
  ],
  paymentAmount: [
    {
      required: true,
      message: '收款金额不能为空',
      trigger: ['change', 'blur'],
    },
  ],
}
if (title.value === '新增') {
  watch(() => [formData.amount, formData.exchangeRate], () => {
    const num = formData.amount * formData.exchangeRate || undefined
    if (!num) { 
      formData.exchangeRateAmount = undefined 
      return 
    }
    formData.exchangeRateAmount = num.toFixed(2)
  })
  watch(() => formData.customerCode, (n, o) => {
    if (n && n !== o) {
      formData.amount = 0
      formData.serialNoAmountVos = []
      formData.billTotalAmount = 0
    }
  })
  watch(() => formData.currency, (n) => {
    if (n === '1') {
      formData.exchangeRate = 1
      return
    }
    if (formData.currency) {
      getCurrencyFn()
    }
  })
}

const getCurrencyFn = async () => {
  const { data } = await exchangeList({
    pageSize: 0,
    pageNum: 0,
    beforeCurrency: formData.currency })
  currencyList.value = data
}
const cancel = () => {
  formRef.value && formRef.value.resetFields()
  formData.id = undefined
  fileList.value = []
  visible.value = false
}
const confirm = () => {
  validateForm(formRef.value, () => {
    loading.value = true
    const params = new FormData()
    
    fileList.value.forEach(item => {
      if (item.raw) {
        params.append('files', item.raw)
      }
    })
    if (formData.id) {
      params.append('sysExpensesCollectionManagerDto', JSON.stringify(formData))

      collectionManagerEdit(params)
      .then((res) => {
        if (res.code == 200) {
          ElMessage.success('修改成功')
          emits('success')
          cancel()
        }
      })
      .finally(() => {
        loading.value = false
      })
    } else {
      params.append('sysExpensesCollectionManagerDto', JSON.stringify(formData))
      collectionManagerAdd(params)
      .then((res) => {
        if (res.code == 200) {
          ElMessage.success('新增成功')
          emits('success')
          cancel()
        }
      })
      .finally(() => {
        loading.value = false
      })
    }
  })
}

// 上传图片
const uploadFile = () => Promise.resolve()
// 图片上传处理
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type == 'image/gif'
  const isPNG = file.type === 'image/png' || file.type == 'image/gif'
  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  return new Promise((resolve, reject) => {
    if (file.raw) { 
      file = file.raw
    }
    imageConversion.compressAccurately(file, 400).then(res => {
      res = new File([res], file.name, { type: res.type, lastModified: Date.now() })
      resolve(res)
    }).catch(() => {
      reject(false)
    })
  })
}

const open = (t:string, row?:{id:number, [key:string]:any}) => {
  title.value = t
  visible.value = true

  if (row && row.id) {
    nextTick(() => {
      // 临时 后端返回数据未完成
      fileList.value = [{
        name: '222',
        url: row.collectionImg }]
  
      const {
        id,
        customerCode,
        receivingAccount,
        receivingDate,
        transfereeAccountName,
        billTotalAmount,
        currency,
        exchangeRate,
        exchangeRateAmount,
        isBilling,
        receivingRemarks,
        amount,
      } = row

      Object.assign(formData, {
        id,
        customerCode,
        receivingAccount,
        receivingDate,
        transfereeAccountName,
        billTotalAmount,
        currency,
        exchangeRate,
        exchangeRateAmount,
        isBilling,
        receivingRemarks,
        amount,
      })
    })
  }
}

defineExpose({
  open,
})
</script>